package flog

import (
	"fmt"
	"log/slog"
	"os"
	"path/filepath"
)

type LogMode int

const (
	JSONMode LogMode = iota
	TextMode
)

type logger struct {
	Level  slog.Level
	LogOut *os.File
	Mode   LogMode
}

func NewLogger(options ...func(logger *logger)) *slog.Logger {
	l := &logger{}

	for _, option := range options {
		option(l)
	}
	var log *slog.Logger
	switch l.Mode {
	case JSONMode:
		log = slog.New(slog.NewJSONHandler(l.LogOut, &slog.HandlerOptions{
			Level: l.Level,
		}))
	case TextMode:
		log = slog.New(slog.NewTextHandler(l.LogOut, &slog.HandlerOptions{
			Level: l.Level,
		}))
	}

	return log
}

func JSONOut() func(log *logger) {
	return func(log *logger) {
		log.Mode = JSONMode
	}
}

func TextOut() func(log *logger) {
	return func(log *logger) {
		log.Mode = TextMode
	}
}

func DebugMode() func(log *logger) {
	return func(log *logger) {
		log.LogOut = os.Stdout
		log.Level = slog.LevelDebug
	}
}

func ProductionMode(name string) func(log *logger) {
	p, err := os.Executable()
	if err != nil {
		panic(err)
	}
	pa := filepath.Dir(p)
	p = pa

	f, err := os.OpenFile(p+fmt.Sprintf("/%s.log", name), os.O_APPEND|os.O_CREATE|os.O_RDWR, 0700)
	if err != nil {
		panic(err)
	}
	return func(log *logger) {
		log.LogOut = f
		log.Level = slog.LevelError
	}
}
